package com.woniu.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 杨光 微信号:tolryg
 * @time 09:50
 */
@Service
public class UploadService {


    @Resource
    private OSSClient ossClient;

    public String upload(MultipartFile file) {
        //给文件改名字，避免重复
        String uuid = UUID.randomUUID().toString();
        String fileName = file.getOriginalFilename();
        String finalName = uuid+fileName;


        //保存到阿里云oss
        finalName="img/"+finalName;
        ObjectMetadata objectMetadata = new ObjectMetadata();
        try {
            ossClient.putObject(new PutObjectRequest("woniu84woniu84", finalName, file.getInputStream(),objectMetadata));
        } catch (IOException e) {
            return "error";
        }
        return "https://woniu84woniu84.oss-cn-shanghai.aliyuncs.com/"+finalName;
        //保存文件到nginx指定目录
//        File destFile = new File("D:/app/imgs/"+finalName);
//        try {
//            file.transferTo(destFile);
//        } catch (IOException e) {
//            return "error";
//        }

//        return "http://image.wncinema.com/img/"+finalName;


    }
}
